package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.DateFormat
import java.text.SimpleDateFormat

public class autoChatSwitchs implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(autoChatSwitchs.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        DateFormat df = new SimpleDateFormat("HH:mm");
        Date date = new Date();
        String NowTime = df.format(date);
        log.debug("--------------开始执行机器人工作时间切换的配置--------------");
        String getSwitchSQL = "Select Property_Id, Property_Key, Work_Value, No_Work_Value, Work_Time From Property_Value_Switch Where Status = '1'";
        List getSwitchSQLResult = eliteBean.chaxun_sql(getSwitchSQL, "dataSource");
        log.debug("属性配置值集合配置信息：" + getSwitchSQLResult.size());
        if (getSwitchSQLResult.size() > 0) {
            boolean isWorkDate = isWorkDate(eliteBean);
            log.debug("工作日期检验结果：" + isWorkDate);

            // 预处理修改配置计数
            int changePropNum = 0;

            for (int i = 0; i < getSwitchSQLResult.size(); i++) {

                Map getSwitchMap = (Map) getSwitchSQLResult.get(i);

                // 检查是否是工作时间
                String Property_Id = getSwitchMap.get("Property_Id");
                log.debug("Property_Id:" + Property_Id);
                String Property_Key = getSwitchMap.get("Property_Key");
                log.debug("Property_Key:" + Property_Key);
                String Chat_Value = getSwitchMap.get("Work_Value");
                log.debug("Chat_Value:" + Chat_Value);
                if (isWorkDate) {
                    // 当前是工作日期
                    String Work_Time = getSwitchMap.get("Work_Time").toString();
                    String isWorkTime = isWorkTime(Work_Time, NowTime);
                    log.debug("工作时间配置时间检验结果：" + isWorkTime);
                    if (isWorkTime == "0") {
                        Chat_Value = getSwitchMap.get("No_Work_Value");
                    }

                } else {
                    Chat_Value = getSwitchMap.get("No_Work_Value");

                }

                log.debug("工作时间状态对应的配置Value：" + Chat_Value);

                changePropNum += dealChatProperty(eliteBean, Property_Id, Property_Key, Chat_Value);

            }

            log.debug("本次修改Chat配置数量：" + changePropNum);
            if (changePropNum > 0) {
                refreshChatProperty(eliteBean, "refreshProperty");
            }
        } else {
            log.debug("无有效配置...");
        }
        return "执行成功";

    }

    /**
     * 执行网聊配置修改
     * @param eliteBean
     * @param Property_Id
     * @param Property_Key
     * @param Chat_Value
     * @return
     */
    public static int dealChatProperty(EliteBean eliteBean, String Property_Id, String Property_Key, String Chat_Value) {

        String getChatPropertySQL = "Select Value From Property_Value Where Property_Id = '" + Property_Id + "' And Property_Key = '" + Property_Key + "' and rownum = 1";
        List getChatPropertyRes = eliteBean.chaxun_sql(getChatPropertySQL, "dataSource");

        if (getChatPropertyRes.size() > 0) {
            Map getChatPropertyMap = (Map) getChatPropertyRes.get(0);
            String Old_Chat_Value = getChatPropertyMap.get("Value").toString();
            log.debug("当前Chat配置" + Property_Id + "/" + Property_Key + "值:[" + Old_Chat_Value + "]");
            if (Old_Chat_Value.equals(Chat_Value)) {
                log.debug("当前Chat配置和计划修改配置值一致（跳过）");
                return 0;
            } else {
                String insertChatPropHis = "Insert Into Property_Value_His (His_Guid, Property_Id, Property_Key, Property_Key_Name, Value_Old, Value_New, MODIFIEDDATE, MODIFIEDBY) Values (SYS_GUID(), '" + Property_Id +
                        "', '" + Property_Key + "', 'ChatUpdate', '" + Old_Chat_Value + "', '" + Chat_Value + "', sysdate, 'SYSTEM')";
                int insertHis = eliteBean.update(insertChatPropHis, "dataSource");
                log.debug("当前Chat配置His已经新增-影响Row:" + insertHis);

                String updateChatPropSQL = "Update Property_Value Set Value = '" + Chat_Value + "' Where Property_Id = '" + Property_Id + "' And Property_Key = '" + Property_Key + "'";
                if (Chat_Value == null) {
                    updateChatPropSQL = "Update Property_Value Set Value = " + Chat_Value + " Where Property_Id = '" + Property_Id + "' And Property_Key = '" + Property_Key + "'";
                }
                int updateRes = eliteBean.update(updateChatPropSQL, "dataSource");
                log.debug("当前Chat配置已修改-影响Row:" + updateRes);
                return updateRes;

            }

        } else {
            log.debug("当前Chat配置" + Property_Id + "/" + Property_Key + "未配置值");
            String insertChatPropHis = "Insert Into Property_Value_His (His_Guid, Property_Id, Property_Key, Property_Key_Name, Value_Old, Value_New, MODIFIEDDATE, MODIFIEDBY) Values (SYS_GUID(), '" + Property_Id + "', " +
                    "'" + Property_Key + "', 'ChatInsert', '', '" + Chat_Value + "', sysdate, 'SYSTEM')";
            int insertHis = eliteBean.update(insertChatPropHis, "dataSource");
            log.debug("当前Chat配置His已经新增-影响Row:" + insertHis);
            String insertChatPropSQL = "Insert Into Property_Value (Property_Id, Property_Key, Value, Login_Created_By, Login_Modified_By) Values ('" + Property_Id + "', '" + Property_Key + "', '" + Chat_Value + "', 'SELITE', 'SELITE')";
            int insertRes = eliteBean.update(insertChatPropSQL, "dataSource");
            log.debug("当前Chat配置已经新增-影响Row:" + insertRes);
            return insertRes;

        }

    }

    /**
     * 刷新网聊的方法工具
     * @param eliteBean
     * @param ds
     * @param requestType
     * @return
     */
    public static boolean refreshChatProperty(EliteBean eliteBean, String requestType) {

        String NGSDomain = "http://127.0.0.1:8010";
        String ngsTokenURL = NGSDomain + "/EliteGeneralHttpTask/GeneralService/apiNGSToken";
        log.debug("调用ngsTokenURL:" + ngsTokenURL);

        JSONObject apiTokenJson = new JSONObject(Util.doHttpGet(ngsTokenURL, "UTF-8", 5000, 0));
        log.debug("调用ngsTokenURL返回:" + apiTokenJson.toString());

        if (KHUtil.GetJV(apiTokenJson, "code") == "1") {
            String access_token = apiTokenJson.getJSONObject("data").getString("access_token");

            String refreshPropertyURL = NGSDomain + "/webchat/ahr.do?token=" + access_token;
            log.debug("调用网聊刷新URL : " + refreshPropertyURL);

            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

            String refreshBody = "requestType=" + requestType;
            log.debug("调用网聊刷新参数 : " + refreshBody.toString());

            String refreshPropertyResult = Util.doHttpPost(refreshPropertyURL, refreshBody, "UTF-8", 120000, 0);

            log.debug("调用网聊刷新返回: " + refreshPropertyResult);
        } else {
            return false;
        }

    }

    public static String isWorkTime(String Work_Time, String NowTime) {

        // 返回的工作时间类别 0非工作时间 1工作时间 -1不做处理
        String isWorkTime = "0";
        try {
            // 检查是否工作时间
            String[] Work_Time_Arr = Work_Time.split("\\|");

            for (int i = 0; i < Work_Time_Arr.length; i++) {
                String Work_Time_Part = Work_Time_Arr[i];
                log.debug("工作时间-[P-" + (i + 1) + "]:【" + Work_Time_Part + "】");

                boolean isTimeRange = KHUtil.isTimeRange(Work_Time_Part.split("-")[0], NowTime, Work_Time_Part.split("-")[1]);
                log.debug("是否工作时间比较-" + Work_Time_Part.split("-")[0] + "<" + NowTime + ">" + Work_Time_Part.split("-")[1] + " 结果:" + isTimeRange);

                if (isTimeRange) {
                    isWorkTime = "1";
                    break;
                }
            }
        } catch (Exception e) {
            log.warn("是否工作时间比较处理异常(不做处理)-", e);
            isWorkTime = "-1";
        }

        return isWorkTime;

    }

    public static boolean isWorkDate(EliteBean eliteBean) {

        String apiChatWorkTimeURL = KHDBConfig.getParam(eliteBean, "CHAWTI", "") + "?workgroupId=1";
        log.debug("调用网聊工作节假日URL:" + apiChatWorkTimeURL);
        if (KHUtil.isNull(KHDBConfig.getParam(eliteBean, "CHAWTI", "")) || KHUtil.isNull(apiChatWorkTimeURL)) {
            log.debug("网聊工作节假日URL参数未配置...(跳过API日期检查)");
            return true;

        } else {

            try {
                String apiChatWorkTimeRes = Util.doHttpGet(apiChatWorkTimeURL, "UTF-8", 5000, 0);
                log.debug("调用网聊工作节假日结果:" + apiChatWorkTimeRes);

                if (apiChatWorkTimeRes == "0") {
                    // 非工作时间
                    return false;

                } else {
                    return true;
                }

            } catch (Exception e) {
                log.warn("调用网聊工作节假日异常-", e);
                return true;
            }

        }
    }
}